package com.trade.dao.impl;

import com.trade.dao.*;
import com.trade.data.*;
import com.trade.data.type.*;
import java.util.*;
import java.util.zip.*;
import java.text.*;
import org.hibernate.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.io.*;

import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import org.supercsv.cellprocessor.*;
import org.supercsv.io.*;
import org.supercsv.cellprocessor.ift.*;
import org.supercsv.cellprocessor.constraint.*;
import org.supercsv.prefs.*;

import org.json.*;


public class NSEDataDAO extends BaseDAO implements INSEDataDAO{

	Session session = null ;

	CsvPreference PIPE_DELIMITED_HISTORICAL_DATA = new CsvPreference.Builder('"', '|', "\n").build();
	CsvPreference PIPE_DELIMITED = new CsvPreference.Builder('"', '|', "\n").build();

	private static CellProcessor[] getAllStockScriptProcessors() {

			//Company Name,Industry,Symbol,Series,ISIN Code
			//ACC Ltd.,CEMENT AND CEMENT PRODUCTS,ACC,EQ,INE012A01025
			//Ambuja Cements Ltd.,CEMENT AND CEMENT PRODUCTS,AMBUJACEM,EQ,INE079A01024

			final CellProcessor[] processors = new CellProcessor[] {
					new NotNull(), // Company Name,
					new NotNull(), // Industry
					new NotNull(), // Symbol
					new NotNull(), // Series
					new NotNull(), // ISIN Code
			};

			return processors;
	}


	private static CellProcessor[] getStockHistoricalDataProcessors() {

			//date|g1_o|g1_h|g1_l|g1_c|g2

		  final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust!
				StrRegEx.registerMessage(emailRegex, "must be a valid email address");

				final CellProcessor[] processors = new CellProcessor[] {
						new ParseDate("dd-MM-yyyy"), // date
						new ParseDouble(), // open
						new ParseDouble(), // high
						new ParseDouble(), // low
						new ParseDouble(), // close
						new ParseDouble(), // VOLUME
				};


			return processors;
	}

	private static CellProcessor[] getAllUnderlyingIndicesProcessors() {

			//UNDERLYING     SYMBOL    	12-Oct	12-Nov	12-Dec

			final CellProcessor[] processors = new CellProcessor[] {
					new NotNull(), // Index Name,
					new NotNull(), // Symbol
					new Trim(), // 12-oct
					new Trim() , // 12-oct
					new Trim() , // 12-oct

					new Trim(), // 12-oct
					new Trim(), // 12-Nov
					new Trim(), // 12-Dec
					new Trim(), // 12-oct
					new Trim(), // 12-Nov
					new Trim(), // 12-Dec

					new Trim(), // 12-oct
					new Trim(), // 12-Nov
					new Trim(), // 12-Dec
					new Trim(), // 12-oct
					new Trim(), // 12-Nov
					new Trim(), // 12-Dec

			};

			return processors;
	}


	private static CellProcessor[] getAllOptionProcessors() {

			//INSTRUMENT	SYMBOL	EXPIRY_DT	STRIKE_PR	OPTION_TYP	OPEN	HIGH	LOW	CLOSE	SETTLE_PR	CONTRACTS	VAL_INLAKH	OPEN_INT	CHG_IN_OI	TIMESTAMP

			final CellProcessor[] processors = new CellProcessor[] {
					new NotNull(), // INSTRUMENT
					new NotNull(), // Symbol
					new ParseDate("dd-MMM-yyyy"), //EXPIRY_DT
					new NotNull() , // STRIKE_PR
					new NotNull() , // OPTION_TYP
					new ParseDouble(), // OPEN
					new ParseDouble(), // HIGH
					new ParseDouble(), // LOW
					new ParseDouble(), // CLOSE
					new ParseDouble(), // SETTLE_PR
					new ParseDouble(), // CONTRACTS
					new ParseDouble(), // VAL_INLAKH
					new ParseLong(), // OPEN_INT
					new NotNull(), // CHG_IN_OI
					new ParseDate("dd-MMM-yyyy"), // TIMESTAMP
					new Optional(), // 12-Dec
			};

			return processors;
	}


	private static CellProcessor[] getProcessors() {

		  final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+"; // just an example, not very robust!
				StrRegEx.registerMessage(emailRegex, "must be a valid email address");

				final CellProcessor[] processors = new CellProcessor[] {
						new UniqueHashCode(), // customerNo (must be unique)
						new NotNull(), // firstName
						new NotNull(), // lastName
						new ParseDate("dd/MM/yyyy"), // birthDate
						new NotNull(), // mailingAddress
						new Optional(new ParseBool()), // married
						new Optional(new ParseInt()), // numberOfKids
						new NotNull(), // favouriteQuote
						new StrRegEx(emailRegex), // email
						new LMinMax(0L, LMinMax.MAX_LONG) // loyaltyPoints
				};


			return processors;
	}


	private InputStream getStreamWithReplace(InputStream in , int value)throws IOException{
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		int ch ;
		while ((ch = in.read()) > -1){
			if( value == ch ){
				buffer.write((char)10); //new line
			}else{
				buffer.write(ch);
			}
		}

		System.out.println("Stream -"+ new String( buffer.toByteArray() ));

		return new ByteArrayInputStream( buffer.toByteArray());
	}


	public synchronized List<InstrumentVO> getAllStockScripts()throws Exception{
		List<InstrumentVO> instrumentList = new ArrayList<InstrumentVO>();
		try{
				DefaultHttpClient httpclient = new DefaultHttpClient();
				//http://www.nseindia.com/content/indices/ind_niftylist.csv

				HttpGet httpget = new HttpGet("http://www.nseindia.com/content/indices/ind_niftylist.csv");
				httpget.getParams().setParameter("http.socket.timeout",new Integer(20000));

				httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				httpget.setHeader("Accept-Charset",
				"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
				httpget.setHeader("Accept-Encoding", "gzip,deflate");
				httpget.setHeader("Accept-Language", "en-us,en;q=0.5");
				httpget.setHeader("Connection", "keep-alive");

				HttpResponse response = httpclient.execute(httpget);

				ICsvListReader listReader = null;
				try{
					listReader = new CsvListReader(new InputStreamReader(response.getEntity().getContent()), CsvPreference.STANDARD_PREFERENCE); //

					listReader.getHeader(true);

					final CellProcessor[] processors = getAllStockScriptProcessors();

					List<Object> symbolList;
					while( (symbolList = listReader.read(processors)) != null ) {
						InstrumentVO instrumentVO =new InstrumentVO();
						instrumentVO.setSecurityName((String)symbolList.get(0));
						instrumentVO.setMarketType((String)symbolList.get(1));
						instrumentVO.setSymbol((String)symbolList.get(2));
						instrumentVO.setSeries((String)symbolList.get(3));
						instrumentVO.setIsinCode((String)symbolList.get(4));
						instrumentList.add( instrumentVO);
						System.out.println(instrumentVO);
					}

				}finally{
					if( listReader != null ) {
							listReader.close();
					}

				}

		}catch(Exception e){
			throw new Exception(e);
		}
		finally {
		}

		return instrumentList;
	}



	/**
	* This method return Index and Stock historical data.
	*
	*/
	public synchronized List<HistoricalDataVO> getHistoricalData(HistoricalDataFilterVO instrumentVO)throws Exception{
		List<HistoricalDataVO> instrumentHistList = new ArrayList<HistoricalDataVO>();

		Format formatter = new SimpleDateFormat("dd-MM-yyyy");

		try{
				DefaultHttpClient httpclient = new DefaultHttpClient();
				//http://www.nseindia.com/ChartApp/install/charts/data/GetHistoricalNew.jsp

				HttpPost httppost = new HttpPost("http://www.nseindia.com/ChartApp/install/charts/data/GetHistoricalNew.jsp");
				httppost.getParams().setParameter("http.socket.timeout",new Integer(30000));

				httppost.setHeader("Host", "www.nseindia.com");
				httppost.setHeader("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12");
				httppost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				httppost.setHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7");
				httppost.setHeader("Accept-Encoding", "gzip,deflate");
				httppost.setHeader("Accept-Language", "en-us,en;q=0.5");
				httppost.setHeader("Connection", "keep-alive");
				httppost.setHeader("Keep-Alive","115");
				httppost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				httppost.setHeader("Referer","http://www.nseindia.com/ChartApp/install/charts/mainpage.jsp");
				httppost.setHeader("Cookie","pointerfo=1; underlying1=NIFTY; instrument1=OPTIDX; optiontype1=CE; expiry1=25OCT2012; strikeprice1=5800.00");


				Map<String, String> paramKey = new HashMap<String, String>();

				System.out.println("Date - "+formatter.format(instrumentVO.getFromDate()));
				paramKey.put("CDDate1",formatter.format(instrumentVO.getFromDate()));
				paramKey.put("CDDate2",formatter.format(instrumentVO.getToDate()));
				paramKey.put("CDExpiryMonth","1");
				paramKey.put("CDIntraExpiryMonth","29-10-2012");
				paramKey.put("CDSymbol", instrumentVO.getSymbol());
				paramKey.put("FOExpiryMonth","1");
				paramKey.put("FOIntraExpiryMonth","25-10-2012");
				paramKey.put("IRFExpiryMonth","27-03-2013");
				paramKey.put("IRFIntraExpiryMonth","");
				paramKey.put("Instrument","FUTSTK");
				paramKey.put("PeriodType","1");
				paramKey.put("Periodicity","1");
				paramKey.put("Segment",instrumentVO.getSegment());  // CM for Equity and OI for Index
				paramKey.put("Series", instrumentVO.getSeries() ); //EQ
				paramKey.put("ct0","g1|1|1");
				paramKey.put("ct1","g2|2|1");
				paramKey.put("ctcount","2");
				paramKey.put("time","1009829490123");


				List<NameValuePair> nvps = getParam(paramKey);
				httppost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

				HttpResponse response = httpclient.execute(httppost);

				ICsvListReader listReader = null;

				GZIPInputStream zipIn = new GZIPInputStream(response.getEntity().getContent());

				/*Scanner sc = new Scanner(zipIn);
				while(sc.hasNextLine()){
					System.out.println(sc.nextLine());
					System.out.println("\n -------- \n");
				}*/

				//date|g1_o|g1_h|g1_l|g1_c|g2~17-10-2012|2246.2000|2255.9000|2202.1000|2214.7000|2107570~18-10-2012|2228.3500|2283.7000|2207.0000|2278.2000|2427445~19-10-2012|2270.0000|2279.8500|2234.0000|2257.7500|1970000

				try{
					listReader = new CsvListReader(new InputStreamReader(  getStreamWithReplace( zipIn , (int)'~')  ), PIPE_DELIMITED_HISTORICAL_DATA);

					listReader.getHeader(true);

					final CellProcessor[] processors = getStockHistoricalDataProcessors();

					List<Object> symbolList;
					while( (symbolList = listReader.read(processors)) != null ) {
						System.out.println("While loop :"+symbolList);
						HistoricalDataVO histDataVO =new HistoricalDataVO();

						histDataVO.setSymbol(instrumentVO.getSymbol());
						histDataVO.setDate( (Date)symbolList.get(0));
						histDataVO.setOpen( (Double)symbolList.get(1) );
						histDataVO.setHigh( (Double)symbolList.get(2) );
						histDataVO.setLow( (Double)symbolList.get(3) );
						histDataVO.setClose( (Double)symbolList.get(4) );
						histDataVO.setVolume( (Double)symbolList.get(5) );
						instrumentHistList.add( histDataVO);

						System.out.println("Equity - "+histDataVO);
					}

				}finally{
					if( listReader != null ) {
							listReader.close();
					}
				}

				System.out.println("Equity - "+instrumentHistList);

		}catch(Exception e){
			System.out.println("Equity - "+e);
			throw new Exception(e);
		}
		finally {
		}

		return instrumentHistList;
	}


	private synchronized List<NameValuePair> getParam(Map<String, String> map) {
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		Set<String> set = map.keySet();
		for (String s : set) {
			  param.add(new BasicNameValuePair(s, map.get(s) != null ? map.get(s) : ""));
		}
		return param;
	}


	/**
	*
	*
	*/
	public synchronized List<IndexVO> getAllIndicesData()throws Exception{

		List<IndexVO> instrumentList = new ArrayList<IndexVO>();
		try{
				DefaultHttpClient httpclient = new DefaultHttpClient();
				//http://www.nseindia.com/content/fo/fo_mktlots.csv


				HttpGet httpget = new HttpGet("http://www.nseindia.com/content/fo/fo_mktlots.csv");
				httpget.getParams().setParameter("http.socket.timeout",new Integer(20000));

				httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				httpget.setHeader("Accept-Charset",
				"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
				httpget.setHeader("Accept-Encoding", "gzip,deflate");
				httpget.setHeader("Accept-Language", "en-us,en;q=0.5");
				httpget.setHeader("Connection", "keep-alive");

				HttpResponse response = httpclient.execute(httpget);

				ICsvListReader listReader = null;
				try{
					listReader = new CsvListReader(new InputStreamReader(response.getEntity().getContent()), CsvPreference.STANDARD_PREFERENCE); //

					listReader.getHeader(true);

					final CellProcessor[] processors = getAllUnderlyingIndicesProcessors();

					List<Object> symbolList;
					while( (symbolList = listReader.read(processors)) != null ) {
						if( "Derivatives on Individual Securities".contains((String)symbolList.get(0) )){
							break;
						}
						IndexVO instrumentVO =new IndexVO();
						instrumentVO.setSecurityName((String)symbolList.get(0));
						instrumentVO.setSymbol((String)symbolList.get(1));
						System.out.println( "Lot size "+ (String)symbolList.get(2));
						if( (String)symbolList.get(2) != null && ((String)symbolList.get(2)).trim().length() > 0   ){
							instrumentVO.setFoMarketLotSize(Integer.parseInt((String)symbolList.get(2)));
						}else if( (String)symbolList.get(3) != null && ((String)symbolList.get(3)).trim().length() > 0   ){
							instrumentVO.setFoMarketLotSize(Integer.parseInt((String)symbolList.get(3)));
						}

						instrumentList.add( instrumentVO);
						System.out.println(instrumentVO);
					}

				}finally{
					if( listReader != null ) {
							listReader.close();
					}

				}

		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e);
		}
		finally {
		}

		return instrumentList;

	}


	/**
	*
	*
	*/
	public synchronized List<InstrumentVO> getAllStockDerivativeMarketLot()throws Exception{

		List<InstrumentVO> instrumentList = new ArrayList<InstrumentVO>();
		try{
				DefaultHttpClient httpclient = new DefaultHttpClient();
				//http://www.nseindia.com/content/fo/fo_mktlots.csv


				HttpGet httpget = new HttpGet("http://www.nseindia.com/content/fo/fo_mktlots.csv");
				httpget.getParams().setParameter("http.socket.timeout",new Integer(20000));

				httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				httpget.setHeader("Accept-Charset",
				"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
				httpget.setHeader("Accept-Encoding", "gzip,deflate");
				httpget.setHeader("Accept-Language", "en-us,en;q=0.5");
				httpget.setHeader("Connection", "keep-alive");

				HttpResponse response = httpclient.execute(httpget);

				ICsvListReader listReader = null;
				try{
					listReader = new CsvListReader(new InputStreamReader(response.getEntity().getContent()), CsvPreference.STANDARD_PREFERENCE); //

					listReader.getHeader(true);

					final CellProcessor[] processors = getAllUnderlyingIndicesProcessors();

					List<Object> symbolList;
					boolean found = false;
					while( (symbolList = listReader.read(processors)) != null ) {
						//Continue till Equity date label
						if( found == false && "Derivatives on Individual Securities".contains((String)symbolList.get(0) )){
							found = true;
							continue;
						}

						if( found == true){
							InstrumentVO instrumentVO =new InstrumentVO();
							instrumentVO.setSecurityName((String)symbolList.get(0));
							instrumentVO.setSymbol((String)symbolList.get(1));
							System.out.println( "Lot size "+ (String)symbolList.get(2));
							if( (String)symbolList.get(2) != null && ((String)symbolList.get(2)).trim().length() > 0   ){
								instrumentVO.setFoMarketLotSize(Integer.parseInt((String)symbolList.get(2)));
							}else if( (String)symbolList.get(3) != null && ((String)symbolList.get(3)).trim().length() > 0   ){
								instrumentVO.setFoMarketLotSize(Integer.parseInt((String)symbolList.get(3)));
							}

							instrumentList.add( instrumentVO);
							System.out.println(instrumentVO);
						}
					}

				}finally{
					if( listReader != null ) {
							listReader.close();
					}

				}

		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e);
		}
		finally {
		}

		return instrumentList;

	}




	public synchronized List<OptionDataVO> getAllOptionScrips(InstrumentVO instrumentVO)throws Exception{

		//http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/ajaxFOGetQuoteDataTest.jsp?i=OPTSTK&u=NIFTY&e=&o=&k=
		//http://www.nseindia.com/content/historical/DERIVATIVES/2012/OCT/fo19OCT2012bhav.csv.zip
		//INSTRUMENT SYMBOL	EXPIRY_DT	STRIKE_PR	OPTION_TYP	OPEN	HIGH	LOW	CLOSE	SETTLE_PR	CONTRACTS	VAL_INLAKH	OPEN_INT	CHG_IN_OI	TIMESTAMP
		//OPTSTK,ZEEL,27-Dec-2012,250,PE,0,0,0,61.35,55.2,0,0,0,0,19-OCT-2012,

		DateFormat formatter = new SimpleDateFormat("ddMMMyyyy");
		NumberFormat numberFormatter = NumberFormat.getInstance();


		List<OptionDataVO> instrumentList = new ArrayList<OptionDataVO>();
		try{
				DefaultHttpClient httpclient = new DefaultHttpClient();

				HttpGet httpget = new HttpGet("http://www.nseindia.com/content/historical/DERIVATIVES/2012/OCT/fo19OCT2012bhav.csv.zip");
				httpget.getParams().setParameter("http.socket.timeout",new Integer(20000));

				httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				httpget.setHeader("Accept-Charset",
				"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
				httpget.setHeader("Accept-Encoding", "gzip,deflate");
				httpget.setHeader("Accept-Language", "en-us,en;q=0.5");
				httpget.setHeader("Connection", "keep-alive");

				HttpResponse response = httpclient.execute(httpget);

				ByteArrayInputStream bis = null;
				ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(response.getEntity().getContent()));

				ZipEntry entry = null;
				while ((entry = zipIn.getNextEntry()) != null)
				{
					System.out.println("entry: " + entry.getName() + ", " + entry.getSize());

					StringBuffer sb = new StringBuffer();
					for (int c = zipIn.read(); c != -1; c = zipIn.read()) {
					  sb.append((char)c);
					}

					//System.out.println(sb.toString());
					bis = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
					zipIn.closeEntry();

					break;
				}



				ICsvListReader listReader = null;
				try{
					listReader = new CsvListReader(new InputStreamReader (bis ), CsvPreference.STANDARD_PREFERENCE); //

					listReader.getHeader(true);

					final CellProcessor[] processors = getAllOptionProcessors();

					List<Object> symbolList;
					boolean found = false;
					while( (symbolList = listReader.read(processors)) != null ) {
						OptionDataVO optionActiveScriptVO = new OptionDataVO();

						optionActiveScriptVO.setInstrumentType( InstrumentTypes.getByValue( (String)symbolList.get(0) ) );
						optionActiveScriptVO.setSymbol( (String)symbolList.get(1) );
						optionActiveScriptVO.setExpiryDate( (Date)symbolList.get(2) );
						optionActiveScriptVO.setStrikePrice( (String)symbolList.get(3) );
						optionActiveScriptVO.setOptionType( OptionTypes.getByValue( (String)symbolList.get(4)  ));
						optionActiveScriptVO.setOpenInterest((Long)symbolList.get(12) );

						System.out.println(optionActiveScriptVO.getSymbol()+" , "+optionActiveScriptVO.getExpiryDate()+" , "+optionActiveScriptVO.getStrikePrice());
						instrumentList.add( optionActiveScriptVO );


					}

				}finally{
					if( listReader != null ) {
							listReader.close();
					}

				}

		}finally{
		}

		return instrumentList;

	}





	public synchronized List<OptionDataVO> getActiveOptionScrips()throws Exception{

		//http://www.nseindia.com/live_market/dynaContent/live_analysis/most_active/CallsALLVolume.json
		//http://www.nseindia.com/live_market/dynaContent/live_analysis/most_active/PutsALLVolume.json
		//http://www.nseindia.com/live_market/dynaContent/live_analysis/most_active/PutsOPTSTKVolume.json
		//http://www.nseindia.com/live_market/dynaContent/live_analysis/most_active/CallsOPTSTKVolume.json

		DateFormat formatter = new SimpleDateFormat("ddMMMyyyy");
		NumberFormat numberFormatter = NumberFormat.getInstance();


		List<OptionDataVO> instrumentList = new ArrayList<OptionDataVO>();
		try{
				DefaultHttpClient httpclient = new DefaultHttpClient();

				HttpGet httpget = new HttpGet("http://www.nseindia.com/live_market/dynaContent/live_analysis/most_active/CallsALLVolume.json");
				httpget.getParams().setParameter("http.socket.timeout",new Integer(20000));

				httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
				httpget.setHeader("Accept-Charset",
				"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
				httpget.setHeader("Accept-Encoding", "gzip,deflate");
				httpget.setHeader("Accept-Language", "en-us,en;q=0.5");
				httpget.setHeader("Connection", "keep-alive");

				HttpResponse response = httpclient.execute(httpget);

				try{

					Scanner sc = new Scanner(response.getEntity().getContent());
					StringBuffer sb = new StringBuffer();
					while(sc.hasNextLine()){
						sb.append(sc.nextLine());
					}

					JSONObject json = new JSONObject( sb.toString());

					JSONArray jsonArray = json.getJSONArray("data");

					for(int i = 0 ; i < jsonArray.length() ; i++){
						OptionDataVO optionActiveScriptVO = new OptionDataVO();

						JSONObject jsonObject = jsonArray.getJSONObject(i);

						optionActiveScriptVO.setSymbol( jsonObject.getString("symbol") );
						optionActiveScriptVO.setExpiryDate( formatter.parse( jsonObject.getString("expiryDate")) );
						optionActiveScriptVO.setInstrumentType( InstrumentTypes.getByValue( jsonObject.getString("instrumentType") ) );
						optionActiveScriptVO.setOptionType( OptionTypes.getByValue( jsonObject.getString("optionType") ));
						optionActiveScriptVO.setStrikePrice( jsonObject.getString("strikePrice") );
						optionActiveScriptVO.setLastTradePrice( jsonObject.getDouble("lastTradedPrice") );

						optionActiveScriptVO.setVolume(numberFormatter.parse( jsonObject.getString("noOfContractsTraded") ).longValue() );
						optionActiveScriptVO.setOpenInterest(numberFormatter.parse( jsonObject.getString("openInterest") ).longValue() );
						optionActiveScriptVO.setUnderlyingValue(numberFormatter.parse( jsonObject.getString("valueOfUnderlying") ).doubleValue() );

						System.out.println(jsonObject.getString("symbol")+" , "+jsonObject.getString("expiryDate")+" , "+jsonObject.getString("strikePrice"));
						instrumentList.add( optionActiveScriptVO );
					}

				}finally{
				}

		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e);
		}
		finally {
		}

		return instrumentList;

	}


}